package com.example.aqarapp.view;

import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;

import com.example.aqarapp.entity.DeviceInfo;
import com.example.aqarapp.entity.DeviceListItem;
import com.example.aqarapp.entity.OneBean;
import com.example.aqarapp.view.adapter.CustomSpinnerAdapter;
import com.example.aqarapp.view.dialog.UserPopupWindow;
import com.example.aqarapp.view.fragment.DeviceListFragment;
import com.example.aqarapp.view.fragment.QuickCtlFragment;
import com.example.aqarapp.view.utils.MessageEvent;
import com.example.aqarapp.viewmodel.FamilyInfoViewModel;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import aqarapp.R;

public class MainPageActivity extends AppCompatActivity implements View.OnClickListener {
    private Spinner mHomeLocationSp;
    private ImageView mUserImg;
    private DeviceDisplaySwitchView mSwitchView;
    private RelativeLayout mUserInfoLayout;
    private UserPopupWindow mUserPopupWindow;
    private NavHostFragment navHostFragment;
    private NavController navController;
    private FamilyInfoViewModel mFamilyInfoViewModel;
    private MutableLiveData<List<String>>  mRoomNameInfoLiveData;
    private MutableLiveData<List<DeviceInfo>> mRoomDeviceInfoLivewData;
    private MutableLiveData<List<OneBean>>  mDeviceListItemLivewData;
    private CustomSpinnerAdapter customSpinnerAdapter;
    public static  String curFamilyName;
    public static  String curRoomName;
    public static final int FAMILY_CHANGE = 100;
    private boolean isFirstAccess =true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_page);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        initViewModel();
        initView();
    }

    private void initViewModel() {
        mFamilyInfoViewModel = new ViewModelProvider (this).get(FamilyInfoViewModel.class);
        mRoomNameInfoLiveData = (MutableLiveData<List<String>>) mFamilyInfoViewModel.getRoomNameInfo();
        mRoomDeviceInfoLivewData = (MutableLiveData<List<DeviceInfo>>) mFamilyInfoViewModel.getDeviceInfo();
        mDeviceListItemLivewData = (MutableLiveData<List<OneBean>>) mFamilyInfoViewModel.getDeviceListInfo();
    }

    private void initView() {
        navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment_container);
        navController = navHostFragment.getNavController();
        mHomeLocationSp = findViewById(R.id.home_location_spinner);
        mSwitchView = findViewById(R.id.display_switch_view);
        mUserImg = findViewById(R.id.user_inf_view);
        mUserInfoLayout = (RelativeLayout) LayoutInflater.from(MainPageActivity.this).inflate(R.layout.layout_user_inf, null);
        List<String> mItems =mFamilyInfoViewModel.getFamilyName();
        customSpinnerAdapter = new CustomSpinnerAdapter(this,
                android.R.layout.simple_spinner_item, mItems);
        customSpinnerAdapter.setDropDownViewResource(R.layout.custom_spinner_dropdown_select);
        //绑定Spinner
        mHomeLocationSp.setAdapter(customSpinnerAdapter);
        //设置下拉框高度
        try {
            Field popup = Spinner.class.getDeclaredField("mPopup");
            popup.setAccessible(true);
            // Get private mPopup member variable and try cast to ListPopupWindow
            android.widget.ListPopupWindow popupWindow = (android.widget.ListPopupWindow) popup.get(mHomeLocationSp);
            // Set popupWindow height to 500px
            popupWindow.setHeight(300);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mHomeLocationSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                curFamilyName = customSpinnerAdapter.getItem(position);
                //  curLocation =mFamilyInfoViewModel.getRoomNameList(curFamilyName).get(id);
                List<String> roomNameList = mFamilyInfoViewModel.getRoomNameList(curFamilyName);
                curRoomName =roomNameList.size()>0?roomNameList.get(0):"";
                Log.d("liyao999","onItemSelected curRoomName= "+curRoomName);
                EventBus.getDefault().post(new MessageEvent(FAMILY_CHANGE));
                mRoomNameInfoLiveData.setValue(mFamilyInfoViewModel.getRoomNameList(curFamilyName));
                mRoomDeviceInfoLivewData.setValue(curRoomName.equals("")?null:mFamilyInfoViewModel.getQuickDeviceItem(curRoomName));
                mDeviceListItemLivewData.setValue(curRoomName.equals("")?null:mFamilyInfoViewModel.getAllDeviceListItem(curRoomName));
                //设置switchView
                Log.d("liyao999"," mSwitchView.isChecked(= "+mSwitchView.isChecked());
//                if(!isFirstAccess){
//                    mSwitchView.setChecked(mSwitchView.isChecked());
//                }
//                isFirstAccess = false;
                if(mSwitchView.isChecked()){
                    curRoomName = "全部";
                    mDeviceListItemLivewData.setValue(mFamilyInfoViewModel.getAllDeviceListItem(curRoomName));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        setOnClick();
    }

    private void setOnClick() {
        mSwitchView.setOnClickCheckedListener(new DeviceDisplaySwitchView.onClickCheckedListener() {
            @Override
            public void onClick(boolean checked) {
                ////将room重置第一个,并更新对应UI
                EventBus.getDefault().post(new MessageEvent(FAMILY_CHANGE));//将room重置第一个
                curRoomName = mFamilyInfoViewModel.getRoomNameList(curFamilyName).get(0);
                if(checked){
                    curRoomName = "全部";
                    Log.d("liyao999"," mSwitchView curRoomName= "+curRoomName);
                    mDeviceListItemLivewData.setValue(mFamilyInfoViewModel.getAllDeviceListItem(curRoomName));
                }else{
                    Log.d("liyao999"," mSwitchView curRoomName= "+curRoomName);
                    mRoomDeviceInfoLivewData.setValue(mFamilyInfoViewModel.getQuickDeviceItem(curRoomName));
                }
                navController.navigate(checked? R.id.action_quickCtlFragment_to_deviceListFragment
                        :R.id.action_deviceListFragment_to_quickCtlFragment);
            }
        });

        mUserImg.setOnClickListener(this);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_inf_view:
                mUserPopupWindow = new UserPopupWindow(mUserInfoLayout, 600, 600);
                mUserPopupWindow.setOutsideTouchable(true);
                mUserPopupWindow.showAsDropDown(mUserImg);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mUserPopupWindow != null) {
            if (mUserPopupWindow.getUserInfoDialog() != null) {
                mUserPopupWindow.getUserInfoDialog().dismiss();
            }
            mUserPopupWindow.dismiss();
        }
    }
}
